<script setup>
import { onMounted, ref, nextTick } from "vue";
import { Edit, Delete, View, CloseBold, Unlock } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import axios from "axios";
import { SrtingToNum, levelSrtingToNum } from "@/utils/typeMap";
import {
  getUser,
  getRole,
  postUserAdd,
  getUserModle,
  postUserBatchAdd,
  DElUser, //删除用户
  getUserReset,
  getUserRole,
  postEditUserRole,
} from "@/api/permission";

import { add, get } from "lodash";

const total = ref(0);
const pagenum = ref(1);
const pagesize = ref(7);
const multipleTableRef = ref();
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  // console.log("val", val);
};
const datalist = ref([]);

const rolevalue = ref("");
const selectform = ref({
  role: "",
  stuClass: "",
  name: "",
  uid: "",
});

const defaultModel = {
  role: "",
  stuClass: "",
  name: "",
  uid: "",
};
const roleList = ref([]); //全部职位

const getRoleList = async () => {
  const res = await getRole();
  //   console.log("res", res);
  roleList.value = res.data;
};

const sizeChange = async () => {
  //页面发生变化
  getUserList();
};

const RoleText = ["学生", "学习部管理", "管理员", "学风部管理", "测试管理员"]; //因为要的id还是要映射

const getUserList = async () => {
  // selectform.role
  // console.log("rolevalue", rolevalue.value);
  selectform.value.role = JSON.parse(JSON.stringify(rolevalue.value));
  // console.log("selectform", selectform.value);
  const res = await getUser(pagenum.value, pagesize.value, selectform.value);
  // console.log("res", res);
  if (res.code) {
    ElMessage.error("获取失败");
    return;
  }
  ElMessage.success("获取成功");
  total.value = res.count;
  datalist.value = res.data;
  console.log("list", datalist.value);
};
const removeSelectForm = async () => {
  rolevalue.value = "";
  //清除表单数据
  selectform.value = { ...defaultModel };
  pagenum.value = 1;
  getUserList();
};

onMounted(() => {
  getRoleList();
  // console.log("角色", roleList);
  getUserList();
  //   console.log("用户列表", datalist.value);
});

const stuForm = ref({
  uid: "",
  stuName: "",
  stuClass: "",
  id: "",
  gender: "",
});
const stuformRef = ref();
const sturules = ref({
  uid: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { pattern: /^\d{10}$/, message: "学号必须是10位数字", trigger: "blur" },
  ],
  stuName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    // 可以添加更多规则，比如姓名的长度或字符限制
  ],
  stuClass: [{ required: true, message: "请输入班级", trigger: "blur" }],
  id: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    // 添加身份证号的格式校验
    {
      pattern:
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: "身份证号格式不正确",
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
});

const dialogVisible = ref(false);

const openAdd = async () => {
  dialogVisible.value = true;
  nextTick(() => {
    stuformRef.value.clearValidate(); //清楚校验
  });
};

const RoleVisible = ref(false); //控制权限修改弹窗的按钮
const handleClose = async () => {
  stuForm.value = {};
  uploadfile.value = null;
  dialogVisible.value = false;
  MulVisible.value = false;
  RoleVisible.value = false;
  RoleUid.value = "";
};

const concelAdd = async () => {
  //清空数据
  stuForm.value = {};
  stuformRef.value.resetFields();
  dialogVisible.value = false;
  MulVisible.value = false;
  uploadfile.value = null;
  handleClose();
};

const addUser = async () => {
  const res = await postUserAdd(stuForm.value);
  if (res.code) {
    ElMessage.error("添加失败");
    return;
  }
  ElMessage.success("添加成功");
  handleClose();
  getUserList();
};
import { saveAs } from "file-saver";
import { de } from "element-plus/es/locales.mjs";
const getModel = async () => {
  await getUserModle()
    .then((response) => {
      saveAs(response, "批量导入学生数据模板.xlsx");
    })
    .catch((error) => {
      ElMessage.error("导出失败");
      console.log(error);
    });
};

const MulVisible = ref(false);
const uploadRef = ref();
const uploadfile = ref();

const onSelectFile = (uploadFile) => {
  uploadfile.value = uploadFile.raw;
  // console.log("上传文件", uploadFile.raw);
};

const handleExceed = (files, uploadFiles) => {
  // 当文件超出限制时，清除之前的文件
  uploadfile.value = files[0];
  uploadRef.value.clearFiles();
  uploadRef.value.handleStart(files[0]);
};
const addMulUser = async () => {
  const fd = new FormData();
  fd.append("file", uploadfile.value);
  const res = await postUserBatchAdd(fd);
  if (res.code) {
    ElMessage.error("添加失败");
    return;
  }
  getUserList();
  ElMessage.success("添加成功");
  handleClose();
};

const RsetPassword = async (uid) => {
  // console.log("重置密码", uid);
  const res = await getUserReset(uid);
  console.log("respass", res);
  if (res.code) {
    ElMessage.error("重置失败");
    return;
  }
  ElMessage.success("重置成功");
};

const delUser = async (id) => {
  const list = ref([]);
  list.value.push(id);
  const res = await DElUser(list.value);
  if (res.code) {
    ElMessage.error("删除失败");
    return;
  }
  ElMessage.success("删除成功");
  getUserList();
};

const delMulUser = async () => {
  const list = multipleSelection.value.map((item) => item.uid);
  if (list.length === 0) {
    ElMessage.error("请选择要删除的用户");
    return;
  }
  const res = await DElUser(list);
  if (res.code) {
    ElMessage.error("删除失败");
    return;
  }
  ElMessage.success("删除成功");
  getUserList();
};

let isCheckList = ref([]);
const RoleUid = ref();
const BeforEditRole = async (uid) => {
  RoleUid.value = uid;
  const res = await getUserRole(uid);
  if (res.code) {
    ElMessage.error("获取用户角色失败");
    return;
  }
  //获得用户角色
  isCheckList.value = res.data;
  console.log("用户角色", res.data);

  nextTick(() => {
    // 显示弹窗
    RoleVisible.value = true;
    console.log(isCheckList.value); // 检查 isCheckList 的值是否正确设置
  });
};

const EditRole = async () => {
  console.log("修改角色", RoleUid.value, isCheckList.value);

  const res = await postEditUserRole(RoleUid.value, isCheckList.value);
  if (res.code) {
    ElMessage.error("修改角色失败");
    return;
  }
  ElMessage.success("修改角色成功");
  RoleVisible.value = false;
  isCheckList.value = [];
  handleClose();
  getUserList();
};
</script>

<template>
  <el-card class="box">
    <div class="top">
      <span style="font-size: 25px; color: #203857">用户管理</span>
      <el-button type="success" @click="openAdd" plain
        ><el-icon><Brush /></el-icon>添加单个用户</el-button
      >
      <el-button type="success" @click="MulVisible = true" plain
        ><el-icon><Sell /></el-icon>批量添加用户</el-button
      >
      <el-button
        @click="getModel"
        text
        type="primary"
        style="margin-left: 1px; line-height: 10px"
        link
        >下载模版</el-button
      >
      <el-button type="warning" @click="delMulUser" plain
        ><el-icon><Timer /></el-icon>批量删除用户</el-button
      >
    </div>
    <el-form :model="selectform" ref="form" inline="true">
      <el-form-item label="用户角色">
        <el-select
          v-model="rolevalue"
          placeholder="请选择用户角色"
          style="height: 35px; width: 150px"
        >
          <el-option
            v-for="(item, index) in roleList"
            :key="index"
            :label="item.roleDescription"
            :value="item.roleId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级">
        <el-input
          style="height: 32px; width: 120px"
          v-model="selectform.stuClass"
          placeholder="请输入班级"
        />
      </el-form-item>
      <el-form-item label="姓名">
        <el-input
          style="height: 32px; width: 120px"
          v-model="selectform.name"
          placeholder="请输入姓名"
        />
      </el-form-item>
      <el-form-item label="学号">
        <!-- 存疑要不要是姓名 -->
        <el-input
          style="height: 32px; width: 120px"
          v-model="selectform.uid"
          placeholder="请输入学号"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 90px" @click="getUserList" plain
          ><el-icon><ZoomIn /></el-icon>筛选</el-button
        >
        <el-button style="width: 90px" @click="removeSelectForm"
          >清除筛选</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      :data="datalist"
      height="500px"
      stripe
      ref="multipleTableRef"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="40" />
      <el-table-column
        type="index"
        label="序号"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="userName"
        label="姓名"
        align="center"
      ></el-table-column>
      <el-table-column prop="uid" label="学号" align="center"></el-table-column>
      <el-table-column
        prop="userDep"
        label="班级"
        align="center"
      ></el-table-column>

      <el-table-column prop="roleDescription" label="用户角色" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right">
        <template #="{ row }">
          <el-button
            title="更改角色"
            type="success"
            size="small"
            text
            link
            plain
            @click="BeforEditRole(row.uid)"
            >更改角色</el-button
          >
          <el-popconfirm
            :title="`确定重置用户全部信息吗？`"
            width="250px"
            icon="Unlock"
            @confirm="RsetPassword(row.uid)"
          >
            <template #reference>
              <el-button
                title="重置"
                type="warning"
                size="small"
                text
                link
                plain
                >重置</el-button
              >
            </template>
          </el-popconfirm>
          <el-popconfirm
            :title="`确定删除吗？`"
            width="250px"
            icon="Delete"
            @confirm="delUser(row.uid)"
          >
            <template #reference>
              <el-button
                title="删除申请"
                plain
                type="danger"
                size="small"
                text
                link
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @size-change="sizeChange"
        @current-change="getUserList"
        :pager-count="9"
        v-model:current-page="pagenum"
        v-model:page-size="pagesize"
        :page-sizes="[3, 5, 7, 9, 15, 30, 60]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </div>
    <el-dialog
      v-model="dialogVisible"
      width="600"
      :before-close="handleClose"
      draggable
    >
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">添加用户</span>
        </div>
      </template>
      <el-form
        label-width="auto"
        :model="stuForm"
        :rules="sturules"
        ref="stuformRef"
      >
        <el-form-item label="姓名" prop="stuName">
          <el-input v-model="stuForm.stuName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="stuForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学号" prop="uid">
          <el-input v-model="stuForm.uid" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="班级" prop="stuClass">
          <el-input v-model="stuForm.stuClass" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="身份证号" prop="id">
          <el-input v-model="stuForm.id" placeholder="请输入身份证号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="concelAdd">取消</el-button>
          <el-button type="primary" @click="addUser"> 确认添加 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="MulVisible" width="300" :before-close="handleClose">
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">上传用户信息</span>
        </div>
      </template>
      <el-upload
        ref="uploadRef"
        :limit="1"
        :on-change="onSelectFile"
        :on-exceed="handleExceed"
        :auto-upload="false"
        ><template #trigger>
          <el-button type="primary" plain size="small">选择文件</el-button>
        </template></el-upload
      >
      <template #footer>
        <div class="dialog-footer">
          <el-button text link @click="concelAdd">取消</el-button>
          <el-button type="primary" text link @click="addMulUser">
            确认添加
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="RoleVisible" width="300" :before-close="handleClose">
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">更改用户角色</span>
        </div>
      </template>
      <!-- 根据roleList显示复选框，v-model绑定ischekList[i] ,roleID为0和2 要禁用-->
      <el-checkbox-group v-model="isCheckList">
        <el-checkbox
          v-for="(item, index) in roleList"
          :key="index"
          :label="item.roleDescription"
          :value="item.roleId"
          :disabled="item.roleId == 0 || item.roleId == 2"
        />
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button text link @click="handleClose">取消</el-button>
          <el-button type="primary" text link @click="EditRole">
            确认添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped lang="scss">
.box {
  padding: 15px;
  // //开启相对定位
  // position: relative;
  // .el-pagination {
  //   position: absolute;
  //   bottom: 25px;
  // }
  .el-table {
    margin-bottom: 2vh;
  }
}
.top {
  display: flex;
  width: 100%;

  height: 50px;
  line-height: 50px;

  //垂直居中
  align-items: center;
  .el-button {
    margin-left: 20px;
  }
  margin-bottom: 15px;
}

.my-header {
  display: flex;
  height: 35px;
  line-height: 35px;
  .titleClass {
    font-size: 15px;
  }
  .imgtitle {
    width: 35px;
    height: 35px;
    margin-right: 10px;
  }
  .titleendClass {
    margin-left: 10px;
    font-size: 20px;
  }
}
</style>
